const { getIssues, getCommentsByIssue, renderMarkdown } = require('./getFromGithub')
// const post2Wordpress = require('./post2Wordpress')
const { post2Ghost, putGhost } = require('./post2Ghost')

async function createPost(issueNumber, title, html, labels, created_at) {
  return { issueNumber, title: /\.png/.test(html) ? '有图' : '', html }
  const postRes = await post2Ghost({
    title: title,
    html: '<!--kg-card-begin: html-->' + html + '<!--kg-card-end: html-->',
    status: "published",
    tags: labels.map(label => label.name),
    created_at: created_at,
    updated_at: created_at,
    published_at: created_at
  })

  if (postRes) {
    return { issueNumber, title, html }
  }
}

async function processIssue(issue) {
  const { number: issueNumber, title, body, labels, created_at } = issue;
  const mdRes = await renderMarkdown(body);
  return createPost(issueNumber, title, mdRes.data, labels, created_at)
}

async function processIssueWithComments(issue) {
  const { number: issueNumber, title, body, labels, created_at } = issue;

  let htmlArr = [];
  const issueMdRes = await renderMarkdown(body)
  htmlArr.push(issueMdRes.data);

  const commentsRes = await getCommentsByIssue(issueNumber)
  const count = commentsRes.data.length;
  for (let i = 0; i < count; i++) {
    const comment = commentsRes.data[i];
    const mdRes = await renderMarkdown(comment.body);
    htmlArr.push(mdRes.data)
  }

  return createPost(issueNumber, title, htmlArr.join(''), labels, created_at);
}

async function init() {
  const issuesRes = await getIssues()
  const count = issuesRes.data.length;
  for (let i = 0; i < count; i++) {
    const issue = issuesRes.data[i];
    const { number: issueNumber, title, body, labels, comments, created_at } = issue;
    let res = null
    // if (issueNumber === 84) {
    //   // res = processIssue(issue)

    //   console.log(issue)
    //   return
    // } else {
    //   continue
    // }
    // console.log(issueNumber, title, comments)
    
    if (comments > 0) {
      res = processIssueWithComments(issue)
    } else {
      res = processIssue(issue)
    }

    if (res) {
      console.log((await res).issueNumber, (await res).title)
    } else {
      return
    }
  }
  
}

init();

// post2Wordpress()

